package com.fitness.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fitness.front.convertor.MemberConvertor;
import com.fitness.front.modal.member.entity.Member;
import com.fitness.front.modal.member.param.MemberPageQueryParams;
import com.fitness.front.modal.member.vo.MemberVO;
import com.fitness.front.modal.response.ServerResponseEntity;
import com.fitness.front.service.IMemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/v1/front/member")
@RequiredArgsConstructor
public class MemberController {

    private final IMemberService memberService;
    private final MemberConvertor memberConvertor;

    @SaCheckLogin
    @GetMapping("/me")
    public ServerResponseEntity<MemberVO> me(HttpServletRequest request){
        String loginId = StpUtil.getLoginIdAsString();
        String[] uidAndUname = loginId.split("_");
        Long uid = Long.parseLong(uidAndUname[0]);
        Member member = memberService.getById(uid);
        MemberVO memberVO = new MemberVO();
        memberVO.setId(uid);
        memberVO.setUsername(member.getUsername());
        memberVO.setAvatar(member.getAvatar());
        return ServerResponseEntity.success(memberVO);
    }

    @SaCheckLogin
    @GetMapping("/getMemberInfo")
    public ServerResponseEntity<MemberVO> getMemberInfo(HttpServletRequest request){
        String loginId = StpUtil.getLoginIdAsString();
        String[] uidAndUname = loginId.split("_");
        Long uid = Long.parseLong(uidAndUname[0]);
        Member member = memberService.getById(uid);
        MemberVO memberVO = memberConvertor.entity2Vo(member);
        memberVO.setSalt(null);
        memberVO.setPassword(null);
        return ServerResponseEntity.success(memberVO);
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ServerResponseEntity<IPage<MemberVO>> page(MemberPageQueryParams queryParams) {
        Page<MemberVO> result = memberService.getUserPage(queryParams);
        return ServerResponseEntity.success(result);
    }

}
